const express = require("express");
const router = express.Router();
const cors = require("cors");
const util = require("util");
const https = require("https");
const url = require("url");
const replacestream = require("replacestream");
const Zlib = require("zlib");

var basicAuth = require("express-basic-auth")

router.use(basicAuth({
  users: {
    "yahoo": "anime65"
  },
  challenge: true,
  realm: "yahoo:anime65"
}))

router.use(async function (req, res) {
  let search_yahoo_url = `https://search.yahoo.co.jp${req.originalUrl}`;
  let parsed_yahoo_url = url.parse(search_yahoo_url);
  let req_headers = req.headers;
  let myhost = req_headers['host'];
  req_headers['host'] && (req_headers['host'] = parsed_yahoo_url.host);
  req_headers['referer'] && (req_headers['referer'] = search_yahoo_url);
  req_headers['origin'] && (req_headers['origin'] = `${parsed_yahoo_url.protocol}//${parsed_yahoo_url.host}`);
  delete req_headers['upgrade-insecure-requests'];
  let https_request = https.request({
    hostname: parsed_yahoo_url.hostname,
    method: req.method,
    headers: req_headers,
    path: parsed_yahoo_url.path,
    // search: parsed_yahoo_url.search
  }, (httpRes) => {
    //处理set-cookie
    //处理headers里面可能出现的location重定向
    if (httpRes.headers) {
      for (let h in httpRes.headers) {
        if (h == "set-cookie") {
          let set_cookies = httpRes.headers['set-cookie'];
          console.log("set_cookies", set_cookies);
          set_cookies.forEach((setCookie, i, arr) => {
            if (setCookie.includes('domain=.yahoo.co.jp')) {
              arr[i] = setCookie.replace("domain=.yahoo.co.jp", `domain=.${myhost}`);
            }
            if (setCookie.includes('domain=.search.yahoo.co.jp')) {
              arr[i] = setCookie.replace("domain=.search.yahoo.co.jp", `domain=.${myhost}`);
            }
          });
          console.log("now set_cookies is", set_cookies);
          res.setHeader("set-cookie", set_cookies);
        } else if (h == "location") {
          let loc = httpRes.headers['location'];
          let parsed_loc = url.parse(loc);
          if (parsed_loc.host == "search.yahoo.co.jp") {
            parsed_loc.host = myhost;
            parsed_loc.hostname = myhost;
            // parsed_loc.protocol = "http:";
          }
          res.setHeader("location", url.format(parsed_loc));
        }
        else if (['p3p', "x-xss-protection", "x-content-type-options", "x-frame-options"].includes(h)) {
          res.setHeader(`X-filtered-${h}`, httpRes.headers[h]);
        }
        else if (h == "content-length") {
          let contentLength = httpRes.headers['content-length'];
          res.setHeader("x-origin-content-length", contentLength);
        }
        else {
          res.setHeader(h, httpRes.headers[h]);
        }
      }
    }
    res.status(httpRes.statusCode);
    //处理html里出现的search.yahoo.co.jp的链接
    if (httpRes.headers['content-type'].includes("text/html")) {
      if (httpRes.headers['content-encoding'] == "gzip") {
        let gunzip = Zlib.createGunzip();
        let gzip = Zlib.createGzip();
        httpRes.pipe(gunzip)
          .pipe(replacestream(`id="SaA-tg-list"`, (raw, ) => {
            return raw.replace(`id="SaA-tg-list"`, `id="FAKEHUJI-SaA-tg-list"`)
          }))
          .pipe(replacestream(`#SaA-tg-list`, (raw, ) => {
            return raw.replace(`#SaA-tg-list`, `#FAKEHUJI-SaA-tg-list`)
          }))
          .pipe(replacestream("https://search.yahoo.co.jp", (raw, ) => {
            return raw.replace("https://search.yahoo.co.jp", `//${myhost}`)
          }))
          .pipe(replacestream("http://search.yahoo.co.jp", (raw, ) => {
            return raw.replace("http://search.yahoo.co.jp", `//${myhost}`)
          }))
          .pipe(replacestream(`"search.yahoo.co.jp"`, (raw, ) => {
            return raw.replace(`"search.yahoo.co.jp"`, `"${myhost}"`)
          }))
          .pipe(replacestream("https://ord.yahoo.co.jp", (raw) => {
            return raw.replace("https://ord.yahoo.co.jp", 'http://ord.yahoocojp.cloudno.de');
          }))
          .pipe(gzip)
          .pipe(res);
      } else {
        httpRes
          .pipe(replacestream(`id="SaA-tg-list"`, (raw, ) => {
            return raw.replace(`id="SaA-tg-list"`, `id="FAKEHUJI-SaA-tg-list"`)
          }))
          .pipe(replacestream(`#SaA-tg-list`, (raw, ) => {
            return raw.replace(`#SaA-tg-list`, `#FAKEHUJI-SaA-tg-list`)
          }))
          .pipe(replacestream("https://search.yahoo.co.jp", (raw, ) => {
            return raw.replace("https://search.yahoo.co.jp", `//${myhost}`)
          }))
          .pipe(replacestream("http://search.yahoo.co.jp", (raw, ) => {
            return raw.replace("http://search.yahoo.co.jp", `//${myhost}`)
          }))
          .pipe(replacestream(`"search.yahoo.co.jp"`, (raw, ) => {
            return raw.replace(`"search.yahoo.co.jp"`, `"${myhost}"`)
          }))
          .pipe(replacestream("https://ord.yahoo.co.jp", (raw) => {
            return raw.replace("https://ord.yahoo.co.jp", 'http://ord.yahoocojp.cloudno.de');
          }))
          .pipe(res);
      }

    }
    else if (httpRes.headers['content-type'].includes("application/javascript")) {
      if (httpRes.headers['content-encoding'] == "gzip") {
        let gunzip = Zlib.createGunzip();
        let gzip = Zlib.createGzip();
        httpRes.pipe(gunzip)
          .pipe(replacestream("https://search.yahoo.co.jp", (raw, ) => {
            return raw.replace("https://search.yahoo.co.jp", `//${myhost}`)
          }))
          .pipe(replacestream("http://search.yahoo.co.jp", (raw, ) => {
            return raw.replace("http://search.yahoo.co.jp", `//${myhost}`)
          }))
          .pipe(replacestream(`"search.yahoo.co.jp"`, (raw, ) => {
            return raw.replace(`"search.yahoo.co.jp"`, `"${myhost}"`)
          }))
          .pipe(replacestream("https://ord.yahoo.co.jp", (raw) => {
            return raw.replace("https://ord.yahoo.co.jp", 'http://ord.yahoocojp.cloudno.de');
          }))
          .pipe(gzip)
          .pipe(res);
      } else {
        httpRes
          .pipe(replacestream("https://search.yahoo.co.jp", (raw, ) => {
            return raw.replace("https://search.yahoo.co.jp", `//${myhost}`)
          }))
          .pipe(replacestream("http://search.yahoo.co.jp", (raw, ) => {
            return raw.replace("http://search.yahoo.co.jp", `//${myhost}`)
          }))
          .pipe(replacestream(`"search.yahoo.co.jp"`, (raw, ) => {
            return raw.replace(`"search.yahoo.co.jp"`, `"${myhost}"`)
          }))
          .pipe(replacestream("https://ord.yahoo.co.jp", (raw) => {
            return raw.replace("https://ord.yahoo.co.jp", 'http://ord.yahoocojp.cloudno.de');
          }))
          .pipe(res);
      }
    }
    else {
      httpRes.pipe(res);
    }

  });

  https_request.on("error", (err) => {
    res.status(500).send({
      error: `https_request.on("error"`,
      detail: err
    })
  });
  req.pipe(https_request);
})



module.exports = router;